import 'dart:async';

import 'package:blue_plugin/bean/characteristic_bean.dart';
import 'package:blue_plugin/bean/dev_info.dart';
import 'package:blue_plugin/bean/dev_state.dart';
import 'package:blue_plugin/bean/scan_result.dart';
import 'package:blue_plugin/blue_elves.dart';
import 'package:blue_plugin/blue_plugin.dart';
import 'package:blue_plugin/utils/date_util.dart';
import 'package:blue_plugin/utils/toast_util.dart';
import 'package:blue_plugin_example/dialog/dialog_blue_select.dart';
import 'package:get/get.dart';
import 'getx_controller_inject.dart';

class BaseBlueController extends BaseGetController {
  String time = DateUtil.getHms();
  bool isOpen = false;
  DevState connectState = DevState.CONNECT;
  bool isScan = false;
  DevInfo? devInfo;
  Timer? _timer;
  int connectTimeout = 1000 * 6; //连接时间
  ScanResults? devBeans;
  BluePlugin? bluePlugin;
  BlueElves? blueInstance;

  @override
  void onInit() {
    super.onInit();
    bluePlugin = BluePlugin();
    blueInstance = bluePlugin?.getBlueElves();
    baseCheckPermission();
  }

  ///连接按钮点击后触发
  baseOnConnectBtn(DevInfo devInfo, {scanTimeout = 10000 * 10}) {
    this.devInfo = devInfo;
    if (isOpen) {
      baseSetConnectMsg(DevState.CONNECTING, "1", "");
      if (connectState == DevState.RECAPTURE) {
        //判断是否在重新采集状态 ，在的话直接 获取获取数据
        if (devBeans == null) {
          baseScanDev();
        } else {
          baseConnectDev(devBeans!);
        }
      } else {
        baseScanDev();
      }
      update();
    } else {
      baseCheckPermission();
    }
  }

  ///设置按钮的状态值
  baseSetConnectMsg(DevState state, String error, String errorMsg) {
    connectState = state;
  }

  ///秒表
  baseGetTime() {
    var timeout = const Duration(seconds: 1);
    _timer = Timer.periodic(timeout, (timer) {
      time = DateUtil.getHms2();
      update();
    });
  }

  ///检查相关权限
  baseCheckPermission() {
    blueInstance!.checkPermission((data, errorMsg) => {
          isOpen = data,
          if (errorMsg.isNotEmpty) {ToastUtils.show(errorMsg + "")}
        });
  }

  ///扫描设备
  baseScanDev() {
    blueInstance!.startScan(
        1000 * 10,
        devInfo!,
        (error, devList) => {
              if (error.isNotEmpty)
                {
                  baseSetConnectMsg(DevState.CONNECT, error, ""),
                  ToastUtils.show(error)
                },
              if (devList.isNotEmpty)
                {
                  if (devList.length == 1)
                    {
                      devBeans = devList[0],
                      print(
                          "找到了${devInfo!.mark}-ids-${devBeans!.id}-name-${devBeans!.name}-uuids-${devBeans!.uuids}"),
                      baseConnectDev(devBeans!),
                    },
                  //弹框
                  if (devList.length > 1)
                    {
                      print("找到多个${devInfo!.mark}"),
                      showSelectDialog(devList),
                    }
                }
            });
  }

  ///找到了 蓝牙设备 连接
  baseConnectDev(ScanResults devBeans) {
    blueInstance!.connect(devBeans, devInfo!.charaList, devInfo!.uuid,
        ((isOk, error) {
      baseSetConnectMsg(DevState.CONNECTING, error, "");
      //连接成功
      if (error == "1") {
        baseReadCharaList();
        baseSetConnectMsg(DevState.COLLECTIONING, error, "");
        baseGetDevValue();
      }
      //连接超时
      if (error == "-1") {
        baseSetConnectMsg(DevState.CONNECT, error, "连接超时");
      }
      //如果是手动断开连接
      if (error == "-2") {
        baseSetConnectMsg(DevState.CONNECT, error, "");
        disConnectBlue();
      }
      //如果是被动断开连接
      if (error == "-3") {
        baseSetConnectMsg(DevState.RECONNECT, error, "");
        disConnectBlue();
      }
    }), connectTimeout: connectTimeout);
  }

  /*** serviceMap
   *   string key 是 serviceUuid
   *   string value  是  List<Map<String, Object>> list
   *   List<Map<String, Object>> list:
   *   Map<String, Object> characteristicInfo = new HashMap<>(2);
      BluetoothGattCharacteristic characteristic = characteristics.get(j);
      characteristicInfo.put("serviceUuid", serviceUuid);
      characteristicInfo.put("uuid", characteristic.getUuid().toString());
      characteristicInfo.put("properties", characteristic.getProperties());
   */

  ///判断初始化的特征值 是否再该设备中包含
  baseReadCharaList() {
    List<CharacteristicBean> characteristicList = [];
    blueInstance!.getCharacteristicBeanAllList((map) => {
          map.forEach((key, value) {
            print("map${key}---${value}");
            List<dynamic> listInfo = value;
            for (int i = 0; i < listInfo.length; i++) {
              Map<dynamic, dynamic> mapInfo = listInfo[i];
              String? uuid = mapInfo["uuid"] as String?;
              int? properties = mapInfo["properties"] as int?;
              if (devInfo!.charaList.contains(uuid)) {
                characteristicList.add(
                    CharacteristicBean(uuid!, devInfo!.uuid, properties!, ""));
              }
            }
          }),
          if (characteristicList.isEmpty) {print("未找到指定特征值")}
        });
  }

  ///根据特征值 去值
  baseGetDevValue() {
    if ((connectState == DevState.COLLECTIONING ||
        connectState == DevState.RECAPTURE)) {
      blueInstance!.readData((isSuccess, data, strdata, uuid) => {
            devValueOpt(isSuccess, data, strdata, uuid),
          });
    }
  }

  /***
   *  if (isSuccess) {
      //成功
      if (devInfo!.devType == DevInfoInit.DEV_TYPE_XUEYA) {
      print("收到的测量数据:${data}");
      if (uuid == DevInfoInit.DEV_XUEYA_TZ_1) {
      print("收到的测量血压最终数据:${data}");
      baseSetConnectMsg(DevState.RECAPTURE, "4", "");
      // setHei(data[1]),
      // setLow(data[3]),
      // setXl(data[14]),
      }

      if (uuid == DevInfoInit.DEV_XUEYA_TZ_2) {
      print("收到的测量血压实时数据:${data}");
      baseSetConnectMsg(DevState.RECAPTURE, "4", "");
      }
      }
      }
   */

  ///根据设备类型 子类做处理
  devValueOpt(bool isSuccess, data, String strdata, String uuid) {}

  destroyBlue() {
    blueInstance!.disConnectBlue();
    blueInstance!.destroyBlue();
    devInfo = null;
    devBeans = null;
  }

  disConnectBlue() {
    blueInstance!.disConnectBlue();
  }

  showSelectDialog(List<ScanResults> devList) {
    Get.dialog(
      BlueSelectDialog(devList,
          nextTap: (index) => {
                Get.back(),
                devBeans = devList[index],
                baseConnectDev(devBeans!),
              }),
    );
  }

// Get.showDialog(
//     title: "提示",
//     content: "蓝牙未打开",
//     backText: "关闭",
//     nextText: "打开",
//     backVisible: true,
//     nextVisible: true,
//     nextTap: () => optBlueOpen,
//     backTap: () => optBlueClose);
}
